package com.ruoyi.zhgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.zhgd.domain.NAsphaltMatch;
import com.ruoyi.zhgd.domain.NAsphaltMatchType;
import com.ruoyi.zhgd.domain.vo.NAsphaltMatchVo;
import com.ruoyi.zhgd.mapper.NAsphaltMatchMapper;
import com.ruoyi.zhgd.service.INAsphaltMatchService;
import com.ruoyi.zhgd.service.INAsphaltMatchTypeService;
import lombok.RequiredArgsConstructor;
import cn.hutool.json.JSONArray;
import org.springframework.stereotype.Service;
import com.ruoyi.zhgd.domain.bo.NAsphaltMatchHotBo;
import com.ruoyi.zhgd.domain.vo.NAsphaltMatchHotVo;
import com.ruoyi.zhgd.domain.NAsphaltMatchHot;
import com.ruoyi.zhgd.mapper.NAsphaltMatchHotMapper;
import com.ruoyi.zhgd.service.INAsphaltMatchHotService;

import java.math.BigDecimal;
import java.util.*;

/**
 * 热料配置表Service业务层处理
 *
 * @author tll
 * @date 2023-10-12
 */
@RequiredArgsConstructor
@Service
@DS("sjcj")
public class NAsphaltMatchHotServiceImpl implements INAsphaltMatchHotService {

    private final NAsphaltMatchHotMapper baseMapper;

    private final INAsphaltMatchService inAsphaltMatchService;

    private final INAsphaltMatchTypeService inAsphaltMatchTypeService;

    private final NAsphaltMatchMapper nAsphaltMatchMapper;

    /**
     * 查询热料配置表
     */
    @Override
    public NAsphaltMatchHotVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询热料配置表列表
     */
    @Override
    public TableDataInfo<NAsphaltMatchHotVo> queryPageList(NAsphaltMatchHotBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NAsphaltMatchHot> lqw = buildQueryWrapper(bo);
        Page<NAsphaltMatchHotVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询热料配置表列表
     */
    @Override
    public List<NAsphaltMatchHotVo> queryList(NAsphaltMatchHotBo bo) {
        LambdaQueryWrapper<NAsphaltMatchHot> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NAsphaltMatchHot> buildQueryWrapper(NAsphaltMatchHotBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NAsphaltMatchHot> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getMatchId()), NAsphaltMatchHot::getMatchId, bo.getMatchId());
        lqw.eq(bo.getSieveSize() != null, NAsphaltMatchHot::getSieveSize, bo.getSieveSize());
        lqw.eq(bo.getTarget() != null, NAsphaltMatchHot::getTarget, bo.getTarget());
        lqw.eq(bo.getGravel1() != null, NAsphaltMatchHot::getGravel1, bo.getGravel1());
        lqw.eq(bo.getGravel2() != null, NAsphaltMatchHot::getGravel2, bo.getGravel2());
        lqw.eq(bo.getGravel3() != null, NAsphaltMatchHot::getGravel3, bo.getGravel3());
        lqw.eq(bo.getGravel4() != null, NAsphaltMatchHot::getGravel4, bo.getGravel4());
        lqw.eq(bo.getGravel5() != null, NAsphaltMatchHot::getGravel5, bo.getGravel5());
        lqw.eq(bo.getGravel6() != null, NAsphaltMatchHot::getGravel6, bo.getGravel6());
        lqw.eq(bo.getPowder1() != null, NAsphaltMatchHot::getPowder1, bo.getPowder1());
        lqw.eq(bo.getPowder2() != null, NAsphaltMatchHot::getPowder2, bo.getPowder2());
        lqw.eq(bo.getPowder3() != null, NAsphaltMatchHot::getPowder3, bo.getPowder3());
        lqw.eq(bo.getRecycledMaterial() != null, NAsphaltMatchHot::getRecycledMaterial, bo.getRecycledMaterial());
        return lqw;
    }

    /**
     * 新增热料配置表
     */
    @Override
    public Boolean insertByBo(NAsphaltMatchHotBo bo) {
        NAsphaltMatchHot add = BeanUtil.toBean(bo, NAsphaltMatchHot.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改热料配置表
     */
    @Override
    public Boolean updateByBo(NAsphaltMatchHotBo bo) {
        NAsphaltMatchHot update = BeanUtil.toBean(bo, NAsphaltMatchHot.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NAsphaltMatchHot entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除热料配置表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 获取目标级配数据
     *
     * @param matchId 配比主键
     * @return 配比主键
     */
    @Override
    public Map<String, Double> getTargetMap(String matchId) {
        QueryWrapper<NAsphaltMatchHot> queryWrapper = new QueryWrapper<NAsphaltMatchHot>();
        queryWrapper.eq("match_id", matchId);
        queryWrapper.orderByAsc("sieve_size");
        List<NAsphaltMatchHot> list = baseMapper.selectList(queryWrapper);

        Map<String, Double> result = new HashMap<String, Double>();
        if (ObjectUtils.isNotEmpty(list)) {
            String sieve;
            for (NAsphaltMatchHot item : list) {
                if (null != item.getSieveSize()) {
                    sieve = item.getSieveSize().stripTrailingZeros().toPlainString();
                    sieve = sieve.replace(".", "d");
                    result.put(sieve, item.getTarget().doubleValue());
                }
            }
        }
        return result;
    }

    /**
     * 获取指定生产级配热料筛分级配列表
     *
     * @param matchId
     * @return
     */
    @Override
    public List<NAsphaltMatchHot> matchList(String matchId) {
        // 获取级配信息
        NAsphaltMatchVo match = inAsphaltMatchService.queryById(matchId);
        if (null == match) {
            throw new ServiceException("设计生产级配不存在");
        }
        // 获取级配类型
        NAsphaltMatchType matchType = inAsphaltMatchTypeService.getByType(match.getMatchType());
        if (null == matchType) {
            return new ArrayList<NAsphaltMatchHot>();
        }
        // 获取当前已经设置的信息
        QueryWrapper<NAsphaltMatchHot> queryWrapper = new QueryWrapper<NAsphaltMatchHot>();
        queryWrapper.eq("match_id", matchId);
        queryWrapper.orderByAsc("sieve_size");
        List<NAsphaltMatchHot> list = baseMapper.selectList(queryWrapper);
        Map<String, NAsphaltMatchHot> map = new HashMap<>();
        BigDecimal sieveSize;
        if (ObjectUtils.isNotEmpty(list)) {
            for (NAsphaltMatchHot item : list) {
                sieveSize = item.getSieveSize();
                if (null != sieveSize) {
                    map.put(sieveSize.stripTrailingZeros().toPlainString(), item);
                }
            }
        }
        // 根据级配类型筛选出需要显示的数据，防止级配做了修改，数据有差异情况
        JSONArray sieveArray = new JSONArray(matchType.getSieveArray());
        List<NAsphaltMatchHot> result = new ArrayList<NAsphaltMatchHot>();
        if (null != sieveArray) {
            NAsphaltMatchHot entity;
            for (int i = 0, len = sieveArray.size(); i < len; i++) {
                try {
                    sieveSize = sieveArray.getBigDecimal(i);
                    if (null != sieveSize) {
                        entity = map.get(sieveSize.stripTrailingZeros().toPlainString());
                        if (null == entity) {
                            entity = new NAsphaltMatchHot();
                            entity.setMatchId(match.getId());
                            entity.setSieveSize(sieveSize);
                        }
                        result.add(entity);
                    }
                } catch (Exception e) {
                }
            }
        }

        return result;
    }

    /**
     * 添加配比热料筛分级配
     *
     * @param list
     * @param matchId
     */
    @Override
    public void save(List<NAsphaltMatchHot> list, String matchId) {
        // 删除已存在的数据
        QueryWrapper<NAsphaltMatchHot> wrapper = new QueryWrapper<>();
        wrapper.eq("match_id",matchId);
        baseMapper.delete(wrapper);

        //添加新的数据
        list.forEach(item -> {
            item.setId(null);
            item.setMatchId(matchId);
        });
        list.stream().forEach(t -> {
            ValidatorUtils.validate(t);
        });
        baseMapper.insertOrUpdateBatch(list);

        // 更新配比热料配置状态
        NAsphaltMatch match = nAsphaltMatchMapper.selectById(matchId);
        match.setHotConfig(1L);
        nAsphaltMatchMapper.updateById(match);
    }
}
